using System.Collections.Generic;
using SimpleJSON;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class ListItemHelper : NodeHelper
    {
        public bool button;
        public AudioClip clip;
        public SoundType soundType;
        public UIEvent uiEvent;

        [SelectRef(UIKey.DATA_KEY)] public SelectKey disabledKey;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey selectKey;
        public bool invert;
        public bool isCache;
        public List<NodeHelper> selectList;
        private Button _Button;
        private JSONObject _json;

        protected Button Button
        {
            get
            {
                if (_Button == null) _Button = UnityTools.GetComponentRequire<Button>(gameObject);
                return _Button;
            }
        }

        protected override void Start()
        {
            if (button && Button != null) Button.onClick.AddListener(BindClick);
        }

        public override void SetData(JSONObject json)
        {
            if (isCache && _json != null && _json == json) return;
            _json = json;
            base.SetData(json);
            if (button && Button != null && !disabledKey.IsEmpty())
                Button.interactable = invert ? disabledKey.Get(json).AsBool : !disabledKey.Get(json).AsBool;
            if (!selectKey.IsEmpty()) SetSelect(selectKey.Get(json));
        }

        public void SetSelect(bool s)
        {
            if (selectList.Count == 0) return;
            for (var i = 0; i < selectList.Count; i++) selectList[i].SetData(s);
        }

        private void BindClick()
        {
            if (uiEvent != UIEvent.None)
                Emit(uiEvent);
            else
                Click();

            if (soundType != SoundType.None)
                Game.single.PlayEFF(soundType);
            else if (clip != null) Game.single.PlayEFF(clip);
        }
    }
}